<!--
 * @Description: 健康登记--预览页
 * @Autor: luojie
 * @Date: 2021-07-08 21:44:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-29 11:26:30
-->

<template>
  <view class="investigate-details-content">
    <view v-for="(rowValue, index) in formData" :key="index">
      <view v-for="item in rowValue" :key="item.name">
        <view v-if="item.maxTitle" class="max-title">{{ item.maxTitle }}</view>
        <!-- <view v-if="item.title" class="max-title">{{ item.title }}</view> -->
        <view v-if="item.subTitle" class="sub-title">{{ item.subTitle }}</view>
        <view class="investigate-row" v-if="item.fieId !== 'screenRegis'">
          <view>{{ item.name }}</view>
          <view v-if="item.fieId != 'ywlxbxs' && item.type != 'select'">
            {{
              item.range
                ? (item.range[item.value].text||'') :
                (Object.prototype.toString.call(item.value) === '[object Object]' ? '' : item.value || '')
            }}
          </view>
          <view v-if="item.type == 'select'">
            {{ item.options[item.value].label==undefined?'':item.options[item.value].label }}
          </view>
        </view>
        <!-- 类型等于input并且，选中为是或为流行病学史  字段 -->
        <view
          v-if="
            item.type == 'input' && (item.value == 1 || item.fieId == 'ywlxbxs')
          "
          class="investigate-details-text"
          >{{ item.inputValue || "" }}
          <!-- <view v-if="item.hasTime">发病时间：{{ item.timeValue }}</view> -->
        </view>
        <view
          v-if="item.type == 'checkBox' && item.value == 1"
          class="investigate-details-text"
        >
          <view v-for="(val, i) in item.checkBoxValue" :key="val.name">
            {{ item.array[val].text }}
            <view class="symbol" v-if="i < item.checkBoxValue.length - 1"
              >、</view
            >
          </view>
        </view>

        <!-- 多选框+选择其他显示输入框 -->
        <view
          v-if="item.type == 'checkBoxOther' && item.value == 1"
          class="investigate-details-text height-auto"
        >
          <view v-for="(val, i) in item.checkBoxValue" :key="val.name">
            {{
              val == item.otherValue
                ? item.array[val - (item.fieId == "jzbs" ? 1 : 0)].text +
                  "：" +
                  item.inputValue
                : (item.array[val - (item.fieId == "jzbs" ? 1 : 0)].text==undefined?(''):(item.array[val - (item.fieId == "jzbs" ? 1 : 0)].text))
            }}
            <view class="symbol" v-if="i < item.checkBoxValue.length - 1"
              >、</view
            >
          </view>
        </view>

        <!-- 下拉框+选择其他显示输入框 -->
        <view
          v-if="item.type == 'selectOther' && item.value == 1"
          class="investigate-details-text"
        >
          {{
            item.selectValue == item.otherValue
              ? item.inputValue
              : item.options[item.selectValue].label
          }}
        </view>

        <!-- 疫苗 -->
        <view v-if="item.type == 'vaccination' && item.value == 1">
          <view
            v-for="val in item.array"
            :key="val.name"
            class="investigate-row"
          >
            <view>{{ val.name }}</view>
            <view
              v-if="
                val.fieId == 'ymdyzcj' ||
                val.fieId == 'ymdezcj' ||
                val.fieId == 'ymdszcj' ||
                val.fieId == 'ymdyzzl' ||
                val.fieId == 'ymdezzl' ||
                val.fieId == 'ymdszzl'
              "
            >
              {{ dealData(val.value, val.options) }}
            </view>
            <view v-else>
              {{ val.value == null || val.value == undefined ? "" : val.value }}
            </view>
          </view>
        </view>
        <!-- 筛查 -->
        <view v-if="item.type == 'screenRegis'">
          <view
            v-for="val in item.array"
            :key="val.name"
            class="investigate-row"
          >
            <view>{{ val.name }}</view>
            <view
              v-if="
                val.fieId == 'ljsc' ||
                val.fieId == 'dgrsc' ||
                val.fieId == 'dgrsc14'
              "
            >
              {{ dealData(val.value, val.options) }}
            </view>
            <view v-else>
              {{ val.value == null || val.value == undefined ? "" : val.value }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="seize-a-seat"></view>
    <view class="footer" v-if="showFooter" :class="onlyRead == '1' ? 'single-footer' : ''">
      <!-- <button class="cancle" @click="goBack">返回</button> -->
      <button class="cancle" @click="goEdit">修改</button>
      <button class="dialogOk" @click="comfirm" v-if="canEdit != '1'">
        确认
      </button>
    </view>
  </view>
</template>

<script>
import { getData,getMedicalObservation } from "../../api/index";
import { investigateCong as formCong } from "./formConfig";
import { cardTypes } from "@/data";

function cpyFunc(obj){
  try {
  return JSON.parse(JSON.stringify(obj));
  } catch (error) {}
};
export default {
  data() {
    return {
      isChange: '0',
      showFooter: true,
      formData: [],
      onlyRead: "",
      canEdit: "",
      // 个人信息
      investigateInfo: cpyFunc(formCong.investigateInfo),
      // 基本信息
      // investigateInfo1: cpyFunc(formCong.baseInfo),
      investigateInfo1: [],
      // 既往病史
      jiBingData: cpyFunc(formCong.jiBingData),
      // 急症病史
      jiZhengData: cpyFunc(formCong.jiZhengData),
      // 服药史
      medicationHistory: cpyFunc(formCong.medicationHistory),
      // 流行病学史
      epidemiologyHis: cpyFunc(formCong.epidemiologyHis),
      // 疫苗
      vaccination: [],
      // 其他史
      otherHistory: cpyFunc(formCong.otherHistory),
      // 心情状态
      currentStatus: cpyFunc(formCong.currentStatus),
      // 紧急联系人
      otherQuestions: cpyFunc(formCong.otherQuestions),
      // 筛选排查
      screenRegis: cpyFunc(formCong.screenRegis),
    };
  },
  filters: {
    sexPD: (value) => {
      if (value == 0) {
        return "女";
      } else if (value == 1) {
        return "男";
      } else {
        return "";
      }
    },
    transVaccineCompanys: (value) => {
      if (value) {
        let text = "";
        vaccineCompanys.forEach((item) => {
          if (value == item.value) {
            text = item.label;
            return;
          }
        });
        return text;
      } else {
        return "";
      }
    },
  },
  components: {},
  onLoad(option) {
    if(option.from && option.from === 'medicalObservation') {
      this.showFooter = false;
    }
    this.onlyRead = option.onlyRead;
    this.canEdit = option.canEdit;
    this.vaccination = cpyFunc([...formCong.vaccination1,...formCong.vaccination2,...formCong.vaccination3])
    this.isChange = option.isChange;
    // if (this.isChange == '1') {
    //   this.showFooter = true;
    // }

    this.setBaseData();

    let formData = uni.getStorageSync("healthScreenData");
    if (formData && formData.length > 0) {
      this.formData = formData;
    } else {
      this.getDataInfo();
    }

  },
  methods: {
    dealData(val, data) {
      let text = "";
      data.forEach((item) => {
        if (val == item.value) {
          text = item.label;
        }
      });
      return text;
    },
    goBack() {
      uni.navigateBack();
    },
    async comfirm() {
      let params = this.handleData();
      let { personId,personClassify,healthRegId,isolateId } = uni.getStorageSync("personInfo");
      params.personId = personId || "";
      params.healthRegId = healthRegId || "";
      params.isolateType = personClassify || '';
      // 注：isolateId从选房页面，根据房间id查询人员信息接口获取，传入此页面。isolateId有值时为修改健康登记
      params.isolateId = isolateId || null;
      let method = 'POST';
      
      if (this.isChange == '1') {
        method = 'PUT'
      }
      getData("healthCheck", method, params).then((res) => {
        uni.navigateTo({
          url: `./success?title=health&isChange=${this.isChange}`,
        });
        uni.removeStorageSync('personInfo')
      });
    },
    // 处理数据
    handleData() {
      let newData = {};
      this.formData[1].forEach((res) => {
        res.fieId && (newData[res.fieId] = res.value);
        res.inputFieId && (newData[res.inputFieId] = res.inputValue);
        // if (
        //   res.type == "checkBox" &&
        //   res.checkBoxValue &&
        //   res.checkBoxValue.length
        // ) {
        //   res.checkBoxValue.forEach((val) => {
        //     val != null && (newData[res.array[val].fieId] = 1);
        //   });
        // }
        // 疫苗接种史
        // if (res.fieId == "ymzs") {
        //   res.array.forEach((item) => {
        //     newData[item.fieId] = item.value;
        //   });
        // }

         if (res.fieId == "ymzsdyzsf" || res.fieId == "ymzsdezsf" || res.fieId == "ymzsdszsf") {
            newData[res.fieId] = res.value!=null && res.value!=undefined ? res.value : 0;
            res.array.map((obj) => {
              newData[obj.fieId] = obj.value;
            });
          }
        // 筛选排查
        if (res.fieId == "screenRegis") {
          res.array.forEach((item) => {
            newData[item.fieId] = item.value;
          });
        }
        // 急症病史
        if (res.fieId == "jzbs") {
          newData[res.inputFieId] = res.inputValue;
          newData[res.fieId] = res.value == 1 ? res.checkBoxValue.join(",") : "0";
        }

        // 流行病学史
        if (res.fieId == "ywlxbxs") {
          newData[res.inputFieId] = res.inputValue;
          delete newData.ywlxbxs;
        }

        // 慢性呼吸系统疾病
        if (res.fieId == "isChronic") {
          if (res.checkBoxValue.length > 0) {
            res.array.forEach((obj, idx) => {
              newData[obj.fieId] = res.checkBoxValue.indexOf(obj.value) > -1 ? 1 : 0
              newData[res.inputFieId] = res.inputValue;
            });
          }
        }
        res.timeValue && (newData[res.timeFieId] = res.timeValue);
      });
      return newData;
    },
    // 给基本信息赋值
    async setBaseData() {
      let {
        name,
        telPhone: phone,
        gender: sex,
        nationality,
        nation,
        hotelContact: isolationPersonInCharge,
        inPostRoomNum,
        moveStartTime,
        personClassify,
        inPostTime,
        age,
        cardId,
        cardType,
        hotelAddr,
        hotelName,
        houseId,
        moveEndTime,
      } = uni.getStorageSync("personInfo");
      let params = {
        cardId,
        cardType,
        hotelAddr,
        hotelName,
        houseId,
        moveStartTime,
        moveEndTime,
        personClassify,
        name,
        phone,
        sex,
        nationality,
        nation,
        age,
        inPostRoomNum,
        isolationPersonInCharge,
        inPostTime,
      };
      this.investigateInfo.forEach((item) => {
        if (item.fieId == "sex") {
          item.value =this.gender(params[item.fieId],params)
          // item.value = params[item.fieId] !== null ? (params[item.fieId] == 1 ? "男" : params[item.fieId]==0?"女":'') : "";
        } else {
          item.value = params[item.fieId];
        }
      });
      let personTypeList = await this.$store.dispatch('getDic','person_classify');
      this.investigateInfo1.forEach((item) => {
        // 人员类型
        if (item.fieId == "personClassify") {
          let arr = personTypeList.filter(obj => {
            return obj.value == params[item.fieId];
          })
          item.value = arr[0] && arr[0].label;
        } else if(item.fieId == 'inPostRoomNum' && params[item.fieId]){
          item.value = params[item.fieId];
        }else if(item.fieId != 'inPostRoomNum'){
          item.value = params[item.fieId];
        }
      });
    },
    gender:function(sex,params){
      // 先判断gender，若没有值则判断身份证倒数第二位，奇数为男，偶数为女
      if (sex == 0) {
        return '女'
      }else if(sex == 1){
        return '男'
      }else{
        if (params.cardType == 0) {
          console.log('身份证倒数第二位：',params.cardId.slice(-2,-1));
          if (params.cardId && params.cardId.slice(-2,-1)%2 == 0 ) {
            return '女'
          }else if(params.cardId && params.cardId.slice(-2,-1)%2 != 0){
            return '男'
          }else{
            return ''
          }
        }else{
          return ''
        }
      }
    },
    getDataInfo() {
      let { personId, isolateId, healthRegId } = uni.getStorageSync("personInfo");
      let params = {
        personId,
        isolateId,
        healthRegId
      };

      // 健康排查查询并且赋值
      getData("healthCheck", "get", params).then((data) => {
        if (data.name) {
          let arr = [
            this.investigateInfo,
            this.jiBingData,
            [this.jiZhengData],
            this.medicationHistory,
            [this.epidemiologyHis],
            this.vaccination,
            this.otherHistory,
            this.currentStatus,
            this.screenRegis,
            this.otherQuestions,
          ];
          arr.forEach((row) => {
            row.forEach((item) => {
              var val = Number(data[item.fieId]);
              if (!isNaN(val)) {
                if (data[item.fieId] == null || item.valueType == "text") {
                  item.value = data[item.fieId] == null ? "" : data[item.fieId];
                } else {
                  item.value = Number(data[item.fieId]);
                }
                if (item.inputFieId) {
                  item.inputValue = data[item.inputFieId];
                }
                // 证件类型
                if (item.fieId == "cardType") {
                  cardTypes.forEach((obj) => {
                    if (obj.value == data[item.fieId]) {
                      item.value = obj.label;
                    }
                  });
                }
              } else {
                item.value = data[item.fieId];
              }
              // 疫苗接种相关
              if (item.fieId == "ymzsdyzsf" || item.fieId == "ymzsdezsf" || item.fieId == "ymzsdszsf") {
                item.value = data[item.fieId];
                item.array.map((obj) => {
                  obj.value = data[obj.fieId];
                });
              }

              // 筛选排查
              if (item.fieId == "screenRegis") {
                item.array.map((obj) => {
                  obj.value = data[obj.fieId];
                });
              }

              // 慢性呼吸系统疾病
              if (item.fieId == "isChronic") {
                let checkBoxValue = [
                  data.isPulmonaryTuberculosis,
                  data.isCopd,
                  data.isEmphysema,
                  data.isAsthma,
                ];
                let value = 0;
                item.checkBoxValue = [];
                if (data[item.fieId] == '1') {
                  checkBoxValue.forEach((obj, idx) => {
                    if (obj == 1) {
                      item.checkBoxValue.push(idx);
                      value = 1;
                    }
                  });
                  if (data[item.inputFieId]) {
                    item.checkBoxValue.push(item.otherValue);
                    value = 1;
                  }
                  item.inputValue = data[item.inputFieId];
                }
                item.value = value;
              }

              // 其他需要关注疾病或情况
              if (item.inputFieId == "otherCondition") {
                if (data[item.inputFieId]) {
                  item.value = 1;
                  item.inputValue = data[item.inputFieId];
                } else {
                  item.value = 0;
                }
              }

              // 急症病史
              if (item.fieId == "jzbs") {
                // 是否
                item.value = data[item.fieId] && data[item.fieId] != '0' ? 1 : 0;
                // 复选框的值
                item.checkBoxValue = data[item.fieId]
                  ? data[item.fieId].split(",")
                  : [];
                // 其他项填写的值
                item.inputValue = data[item.inputFieId] || "";
              }

              // 有时间的话，比如：疟疾等重点传染疾病同史
              if (item.hasTime) {
                item.timeValue = data[item.timeFieId];
              }
              this.investigateInfo1.forEach(item=>{
                if(item.fieId == 'inPostRoomNum'){
                    item.value = data[item.fieId];
                  }
              })
            });
          });

          this.setBaseData();

          this.formData = [
            isolateId,
            healthRegId,
            [...this.investigateInfo, ...this.investigateInfo1],
            [
              ...this.jiBingData,
              this.jiZhengData,
              ...this.medicationHistory,
              this.epidemiologyHis,
              ...this.vaccination,
              ...this.otherHistory,
              ...this.currentStatus,
              ...this.screenRegis,
              ...this.otherQuestions,
            ],
          ];
        }
      });
    },
    goEdit() {
      let route = getCurrentPages();
      let index = route.length-2;
      if(index >= 0 && route[route.length-2].route == "pages/healthInspect/investigate"){
        uni.navigateBack();
      }else{
        uni.navigateTo({
          url: `./investigate?isChange=${this.isChange}`,
        });
      }
    },
  },
};
</script>

<style lang="scss">


.investigate-details-content {
  display: flex;
  flex-direction: column;

  .sub-title {
    font-size: 26rpx;
    line-height: 80rpx;
    font-weight: bold;
    padding: 0 32rpx;
  }

  .investigate-row {
    display: flex;
    justify-content: space-between;
    padding: 0 32rpx;
    // height: 70rpx;
    min-height: 70rpx;
    line-height: 70rpx;

    view:first-child {
      color: #666666;
      font-size: 26rpx;
      min-width: 130rpx;
    }

    view:last-child {
      color: #333333;
      font-size: 30rpx;
      // overflow: hidden;
      // text-overflow: ellipsis;
      // white-space: nowrap;
      flex: 1;
      text-align: right;
      padding-left: 1em;
    }
  }

  .investigate-details-text {
    padding: 0 32rpx;
    color: #666666;
    text-indent: 20rpx;
    font-size: 26rpx;
    min-height: 70rpx;
    line-height: 50rpx;

    & > view {
      display: inline-block;

      .symbol {
        display: inline-block;
      }
    }

    &.height-auto {
      height: auto;
    }
  }

  .max-title {
    font-size: 40rpx;
    color: #000000;
    font-weight: 600;
    height: 98rpx;
    line-height: 98rpx;
    background: #fff;
    border-bottom: 1rpx solid #e5e5e5;
    padding: 0 32rpx;
    position: relative;
  }

  .seize-a-seat {
    height: 80rpx;
    padding: 58rpx 32rpx;
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: space-between;
    padding: 58rpx 32rpx;
    // border: 1rpx solid #cccccc;
    background: #fff;

    .cancle {
      width: 328rpx;
      color: #000000;
      font-size: 34rpx;
      background: #fff;
      border: 1rpx solid #cccccc;
      border-radius: 16rpx;
      margin-right: 30rpx;
    }

    .dialogOk {
      width: 328rpx;
      color: #fff;
      font-size: 34rpx;
      background: #2c9af1;
      border-radius: 16rpx;
    }

    &.single-footer {
      width: 100%;
      justify-content: center;
      align-items: center;

      .cancle {
        margin: 0 auto;
      }
    }
  }
}
</style>
